package cn.com.generaldata.os.ws.impl.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import cn.com.generaldata.jsme_indicator_system.entity.ReportTypeLimit;
import cn.com.generaldata.jsme_indicator_system.entity.StatSystem;
import cn.com.generaldata.jsme_indicator_system.vo.reportdesigner.ReportExcelSectionVO;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.exporter.Exporter;
import cn.com.generaldata.os.importer.Importer;
import cn.com.generaldata.os.newpojo.ReportVersion;
import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.DustryReport;
import cn.com.generaldata.os.pojo.ReportDetail;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.pojo.mvc.Row;
import cn.com.generaldata.os.result.ReportVersionYearRangeResult;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.HistoryService;
import cn.com.generaldata.os.service.common.MarkingService;
import cn.com.generaldata.os.service.common.ReportTemplateService;
import cn.com.generaldata.os.service.common.ReportTypeService;
import cn.com.generaldata.os.service.common.StatSystemService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.web.ReportEIServiceForWeb;
import cn.com.generaldata.os.service.impl.web.ReportServiceForWeb;
import cn.com.generaldata.os.service.impl.web.UnitServiceForWeb;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.ReportAttachVO;
import cn.com.generaldata.os.vo.ReportHistoryVO;
import cn.com.generaldata.os.vo.ReportMarkingVO;
import cn.com.generaldata.os.vo.ReportPerformVO;
import cn.com.generaldata.os.vo.ReportTypeVO;
import cn.com.generaldata.os.vo.ReportVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.VersionVO;
import cn.com.generaldata.os.zip.ZipCompressor;

import com.google.common.collect.Lists;

@Component
@InjectName
public class ReportAction {

	@Autowired
	private ReportTypeService reportTypeService;

	@Autowired
	@Qualifier("reportServiceForWeb")
	private ReportServiceForWeb reportServiceForWeb;

	@Autowired
	@Qualifier("reportEIServiceForWeb")
	private ReportEIServiceForWeb reportEIService;

	@Autowired
	private UserService userService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private AreaService areaService;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<SystemCodedic> sysCodedicDAO;

	@Autowired
	private ReportTemplateService reportTemplate;

	@Autowired
	@Qualifier("indicatorSystemSqlTemplate")
	private SqlTemplate indicatorSystemSqlTemplate;

	@Autowired
	private StatSystemService statSystemService;

	@Autowired
	@Qualifier("unitServiceForWeb")
	private UnitServiceForWeb unitService;

	private static Logger log = LoggerFactory.getLogger(ReportAction.class);

	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM");

	@Autowired
	private MarkingService markingService;

	private Exporter exporter;
	private Date date;
	List<String> urlList;
	private String url;

	private static final String EXPORT_ROOT_DIR = "D:";
	private static final String EXPORT_ROOT_DIR_1 = "apachetomcat6018/webapps/jsme-das-lan/files";
	private static final String EXPORT_FILE = "export_report";
	private static final String EXPORT_FILE_BACKUP = "export_report_backup";

	@At("/company/report/queryTypeNo/?")
	@Ok("json")
	public List<ReportTypeVO> queryTypeNo(Integer type) {
		List<String> queryTypeNo = reportServiceForWeb.queryTypeNo(type);
		List<ReportTypeVO> list = Lists.newArrayList();
		for (String typeNo : queryTypeNo) {
			if (typeNo == null)
				continue;
			ReportTypeVO rt = new ReportTypeVO();
			rt.setTypeNo(typeNo);
			list.add(rt);
		}
		return list;
	}

	public ResultVO<ReportVO> queryReports(String userId, Short checkStatus, String reportTypeNo,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	public void modiAttachDisposal(String attachId, String attachDisposal) {
		reportServiceForWeb.modiAttachDisposal(attachId, attachDisposal);
	}

	public void modiReportAttachsDisposal(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			reportServiceForWeb.modiReportAttachsDisposal(arrIds);
		}
	}

	// 查询当前企业所有的上传附件

	public ResultVO<ReportAttachVO> queryReportAttach(String loginName, Date searchDate, Date endDate, Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		// 如果查询用户ID不为空，就是企业查询，管理部门传null查询全部
		if (StringUtils.isNotBlank(loginName)) {
			User userById = userService.queryUserById(loginName);
			Filter filter2 = new Filter();
			filter2.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", userById.getUserUnit().getId()));
			cn.com.generaldata.os.paging.Result result = userService.queryUsers(filter2, null);
			if (result != null) {
				List<User> operationResult = (List<User>) result.getOperationResult();
				String[] uids = new String[operationResult.size()];
				for (int i = 0; i < operationResult.size(); i++) {
					uids[i] = operationResult.get(i).getId();
				}
				if (!(operationResult.size() > 0)) {
					uids = new String[] { "" };
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "userId", uids));
			} else {
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "userId", loginName));
			}
		}
		// 状态为3的是管理部门发送通知的附件
		filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "isDisposal", 3));
		if (searchDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(searchDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "sysCreateDate", calendar.getTime()));
		}

		if (endDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.LT, "sysCreateDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReportAttach(reportServiceForWeb.queryReportAttach(filter, page));
	}

	// 查询本级企业所有的上传附件

	public ResultVO<ReportAttachVO> queryHandleAttach(String userAreaId, Date searchDate, Date endDate, Integer pageNum) {

		String hql = "select F from ReportAttach F ,User U, " + " Area A where F.userId = U.id and U.area.id = A.id ";
		HashMap map = new HashMap();
		// 如果查询用户ID不为空，就是企业查询，管理部门传null查询全部
		if (StringUtils.isNotBlank(userAreaId)) {

			hql += " and A.id=:userAreaId";
			map.put("userAreaId", userAreaId);

		}
		// 状态为3的是管理部门发送通知的附件
		// filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "isDisposal", 3));
		hql += " and F.isDisposal<>3";
		if (searchDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(searchDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			// filter.addRule(new FilterRule(FilterConstant.GE, "sysCreateDate", calendar.getTime()));
			hql += " and F.sysCreateDate >=:startDate";
			map.put("startDate", calendar.getTime());
		}

		if (endDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			hql += " and F.sysCreateDate <:endDate";
			map.put("endDate", calendar.getTime());
			// filter.addRule(new FilterRule(FilterConstant.LT, "sysCreateDate", calendar.getTime()));
		}
		hql += " order by F.sysCreateDate desc";

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReportAttach(reportServiceForWeb.queryReportAttachByHql(hql, map, page));
	}

	/**
	 * 导入报表
	 * 
	 * @param reportOperatorId
	 * @param reportProxyId
	 * @param reportTypeId
	 * @param timeType
	 * @param yearType
	 * @param timeDate
	 * @param unitIndustryId
	 * @param reportVersion
	 * @param quarterDate
	 * @param content
	 * @param fileName
	 * @param fileType
	 * @return
	 * @throws IOException
	 */

	public String importReport(String reportOperatorId, String reportProxyId, String reportTypeId, String timeType,
			String yearType, String timeDate, String unitIndustryId, String reportVersion, String quarterDate,
			byte[] content, String fileName, String fileType) {
		// 获取报表季度
		String lasttimeQuarterDate = "第零季度";
		String quarterValue = "1";
		if (quarterDate.equals("1")) {
			quarterDate = "第一季度";
			quarterValue = "1";
		}
		if (quarterDate.equals("2")) {
			quarterDate = "第二季度";
			lasttimeQuarterDate = "第一季度";
			quarterValue = "2";
		}
		if (quarterDate.equals("3")) {
			quarterDate = "第三季度";
			lasttimeQuarterDate = "第二季度";
			quarterValue = "3";
		}
		if (quarterDate.equals("4")) {
			quarterDate = "第四季度";
			lasttimeQuarterDate = "第三季度";
			quarterValue = "4";
		}
		cn.com.generaldata.os.pojo.mvc.Report lasttimeReport = new cn.com.generaldata.os.pojo.mvc.Report(); // 上次对比的报表
		// cn.com.generaldata.os.pojo.mvc.Report report = new cn.com.generaldata.os.pojo.mvc.Report();

		// 报表所属用户和操作用户
		if (reportOperatorId == null) {
			return null;
		}
		if (reportTypeId == null) {
			return null;
		}
		Unit unit = unitService.queryUnitById(reportOperatorId);
		// Filter filter=new Filter();
		// filter.addRule(new FilterRule(FilterConstant.COLLECTION, "userUnit.id", unit));
		User user = new User();
		Set<User> users = unit.getUsers();
		if (users == null || !(users.size() > 0)) {
			return null;
		} else {
			user = users.iterator().next();
		}
		// model.put("user", user);
		cn.com.generaldata.os.newpojo.ReportType rType = reportServiceForWeb.queryReportTypeById(reportTypeId);
		// model.put("reportType", rType);

		Properties properties2 = new Properties();
		java.io.InputStream inputstream2 = getClass().getResourceAsStream("/global_conf.properties");
		try {
			properties2.load(inputstream2);
		} catch (Exception ex) {
			log.error("加载配置文件出错", ex);
		}
		String limit = properties2.getProperty("limit").trim();
		if ("true".equals(limit)) {
			Calendar date = Calendar.getInstance();
			//正确填报时间
			Calendar dateOK = Calendar.getInstance();
			// 年
			String yearValue = timeDate.substring(0, 4);
			// 月
			String monthValue = timeDate.substring(5, 7);
			// 不能提前上报
			if (date.get(Calendar.YEAR) < Integer.valueOf(yearValue)) {
				return "error";
			}
			String typeYear = rType.getTypeYearTime();
			//下半年报上半年的
			if ("1".equals(rType.getTypeYearTime())) {
				int month = date.get(Calendar.MONTH);
				if (month > 5)
					typeYear = "4";
			}
			List<ReportTypeLimit> limitList = reportServiceForWeb.queryReportLimit(rType.getStatSystem(), reportTypeId,
					rType.getTypeTime(), typeYear);
			// 催报信息
			Integer timeBill = reportServiceForWeb.queryBillByReport(reportTypeId, user.getUserUnit().getId(),
					timeType, yearType, timeDate, quarterDate);
			if (timeBill == null) {
				timeBill = new Integer(0);
			}
			for (ReportTypeLimit reportLimit : limitList) {
				Integer startDay = reportLimit.getStartDay();
				Integer endDay = reportLimit.getEndDay();
				Integer startMonth = reportLimit.getStartMonth();
				Integer endMonth = reportLimit.getEndMonth();
				// 月报(下月1日+延期)
				if ("0".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
					dateOK.set(Calendar.MONTH, Integer.valueOf(monthValue));
					dateOK.set(Calendar.DATE, startDay);
					if (date.before(dateOK)) {
						return "error";
					}
					dateOK.set(Calendar.DAY_OF_YEAR, dateOK.get(Calendar.DAY_OF_YEAR) + endDay - startDay + timeBill);
					if (date.after(dateOK)) {
						return "error";
					}
					break;
				}
				// 季报
				else if ("2".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					if (Integer.valueOf(quarterValue) == 1) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 3);
					} else if (Integer.valueOf(quarterValue) == 2) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 6);
					} else if (Integer.valueOf(quarterValue) == 3) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, 9);
					} else if (Integer.valueOf(quarterValue) == 4) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue) + 1);
						dateOK.set(Calendar.MONTH, 0);
					}
					dateOK.set(Calendar.DATE, startDay);
					if (date.before(dateOK)) {
						return "error";
					}
					dateOK.set(Calendar.DAY_OF_YEAR, dateOK.get(Calendar.DAY_OF_YEAR) + endDay - startDay + timeBill);
					if (date.after(dateOK)) {
						return "error";
					}
					break;
				}
				// 年报
				else if ("1".equals(timeType) && timeType.equals(reportLimit.getTypeTime())) {
					// 上半年报或全年报
					if (("1".equals(typeYear) || "2".equals(yearType))
							&& reportLimit.getTypeYearTime().equals(typeYear)) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue) + 1);
						dateOK.set(Calendar.MONTH, startMonth - 1);
						dateOK.set(Calendar.DATE, startDay);
						if (date.before(dateOK)) {
							return "error";
						}
						dateOK.set(Calendar.MONTH, endMonth - 1);
						dateOK.set(Calendar.DATE, endDay + timeBill);
						if (date.after(dateOK)) {
							return "error";
						}
					}
					//下半年报
					else if ("4".equals(typeYear) && reportLimit.getTypeYearTime().equals(typeYear)) {
						dateOK.set(Calendar.YEAR, Integer.valueOf(yearValue));
						dateOK.set(Calendar.MONTH, startMonth - 1);
						dateOK.set(Calendar.DATE, startDay);
						if (date.before(dateOK)) {
							return "error";
						}
						dateOK.set(Calendar.MONTH, endMonth - 1);
						dateOK.set(Calendar.DATE, endDay + timeBill);
						if (date.after(dateOK)) {
							return "error";
						}
					}
					continue;
				}
			}
		}
		// 判断当前用户的报表与报表时段是否存在，存在不得保存
		if (reportServiceForWeb.isReportTimeType(user, rType.getId(), timeType, yearType, timeDate, quarterDate,
				reportVersion)) { // 表示已经存在
			return "exist";
		}
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			log.error("加载配置文件出错", ex);
		}
		String saveFileName = fileName; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		saveFileName += String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("上传文件出错", e);
			}
			ReportExcelSectionVO sectionInfo = reportTemplate.getReportExcelSectionInfo(file, reportTypeId);
			// sectionInfo.getReportFootEndRow();
			try {
				reportServiceForWeb.import_report(user, reportProxyId, rType, timeType, yearType, timeDate,
						unitIndustryId, reportVersion, quarterDate, file, sectionInfo);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("报表错误", e);
				return null;
			}
		}
		return fileType;
	}

	public String uploadFile(String loginName, String userUnit, byte[] content, String fileName, String fileType,
			String attachExplain, String status) throws IOException {
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			System.out.print(ex);
		}

		String result = ""; // 添加失败
		ReportAttachVO reportAttach = new ReportAttachVO(); // 文件附件实体
		// String pathFileName; // 附件的全名称，包括路径与文件名
		String saveFileName = loginName; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		System.out.print("上传");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		saveFileName += String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			FileOutputStream stream = new FileOutputStream(file);

			stream.write(content);
			// reportAttach.setAttachId(pathName);
			reportAttach.setAttachFilename(fileName);
			reportAttach.setUserId(loginName);
			reportAttach.setUserUnit(userUnit);
			reportAttach.setSysCreateDate(new Date());
			if (StringUtils.isNotBlank(status)) {
				reportAttach.setIsDisposal(3);// 通知中的附件
			} else {
				reportAttach.setIsDisposal(0); // 为处理的附件
			}
			reportAttach.setAttachPathname(saveFileName);
			reportAttach.setAttachExplain(attachExplain);
			result = this.addReportAttachments(reportAttach); // 将上传的附件信息保存到附件表中
			// result = 1;

			stream.close();
		}

		return result;
	}

	private ReportAttachVO toVoReportAttach(cn.com.generaldata.os.pojo.ReportAttach pReportAttach) {

		if (pReportAttach != null) {
			return new ReportAttachVO(pReportAttach.getAttachId(), pReportAttach.getAttachFilename(),
					pReportAttach.getUserId(), pReportAttach.getUserUnit(), pReportAttach.getSysCreateDate(),
					pReportAttach.getIsDisposal(), pReportAttach.getAttachPathname(), pReportAttach.getAttachExplain());
		}
		return null;
	}

	public ResultVO<ReportAttachVO> queryReportAttachList(String ids) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		if (StringUtils.isNotBlank(ids)) {
			String[] split = ids.split(",");
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "attachId", split));
		}
		return toVoResultReportAttach(reportServiceForWeb.queryReportAttach(filter, null));
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportAttachVO> toVoResultReportAttach(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportAttachVO> result = new ResultVO<ReportAttachVO>();

		List<ReportAttachVO> reportAttachs = new ArrayList<ReportAttachVO>();
		for (cn.com.generaldata.os.pojo.ReportAttach pReportAttach : (List<cn.com.generaldata.os.pojo.ReportAttach>) pResult
				.getOperationResult()) {
			ReportAttachVO voReportAttach = toVoReportAttach(pReportAttach);
			if (voReportAttach != null) {
				reportAttachs.add(voReportAttach);
			}
		}
		result.setOperationResult(reportAttachs);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	// 查询当前ID的上传附件

	public ReportAttachVO queryReportAttachById(String id) {
		cn.com.generaldata.os.pojo.ReportAttach attachById = reportServiceForWeb.queryReportAttachById(id);
		return toVoReportAttach(attachById);
	}

	// 添加附件文件

	public String addReportAttachments(ReportAttachVO reportAttach) {
		return reportServiceForWeb.addReportAttachments(this.toPojoReportAttach(reportAttach));
	}

	public cn.com.generaldata.os.pojo.ReportAttach toPojoReportAttach(ReportAttachVO reportAttach) {
		return new cn.com.generaldata.os.pojo.ReportAttach(null, reportAttach.getAttachFilename(),
				reportAttach.getUserId(), reportAttach.getUserUnit(), reportAttach.getSysCreateDate(),
				reportAttach.getIsDisposal(), reportAttach.getAttachPathname(), reportAttach.getAttachExplain());
	}

	public void removeReportAttachs(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			reportServiceForWeb.removeReportAttachs(arrIds);
		}
	}

	// 根据用户地区查找报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByArea(String userId, String userAreaId, Short checkStatus,
			String reportSystem, String reportTypeNo, String reportVersion, Date startingReportDate,
			Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(userAreaId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		} else if (!StringUtils.isNotBlank(reportTypeNo) && StringUtils.isNotBlank(reportSystem)) {

			Filter typeFilter = new Filter();
			StatSystem ss = statSystemService.getStatSystemByName(reportSystem.trim());
			if (ss != null) {
				typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", ss.getId()));
			}

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}

		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportServiceForWeb.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	public List<SystemCodedic> getSysCode(Filter sysFilter) {
		// sysFilter.addRule(new FilterRule(FilterConstant.EQUAL, "code", pReportType.getStatSystem().toString()));
		// sysFilter.addRule(new FilterRule(FilterConstant.EQUAL, "section", "10012"));
		List<SystemCodedic> find = sysCodedicDAO.find(SystemCodedic.class, sysFilter, null);
		// if (find != null && find.size() > 0) {
		// SystemCodedic systemCodedic = find.get(0);
		// type = systemCodedic.getCodeName();
		// }
		return find;
	}

	// 取得版本类型（三个）

	public List<SystemCodedic> queryType() {
		List<SystemCodedic> list = Lists.newArrayList();
		Map<String, String> statSystems = statSystemService.getStatSystemMap();
		for (Entry<String, String> entry : statSystems.entrySet()) {
			SystemCodedic sc = new SystemCodedic();
			sc.setCode(entry.getKey());
			sc.setCodeName(entry.getValue());
			list.add(sc);
		}
		return list;
	}

	public List<SystemCodedic> queryType(String userId, String roleId) {
		List<SystemCodedic> list = Lists.newArrayList();
		List<StatSystem> statSystems = statSystemService.getStatSystem(userId, roleId);
		for (StatSystem entry : statSystems) {
			SystemCodedic sc = new SystemCodedic();
			sc.setCode(entry.getId().toString());
			sc.setCodeName(entry.getName());
			list.add(sc);
		}
		return list;
	}

	// 根据用户地区查找将要导出的报表 (省级用户导出报表，包括通过的和驳回的)

	public ResultVO<ReportVO> queryExportReportsByArea(String userId, String userAreaId, Short checkStatus,
			String reportTypeNo, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (StringUtils.isNotBlank(userAreaId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportServiceForWeb.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 自加， 根据用户地区和单位查找报表

	public ResultVO<ReportVO> queryReportsByAreaAndUnit(String userId, String userAreaId, Short checkStatus,
			String userUnit, String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 自加， 根据操作人和单位查找报表

	public ResultVO<ReportVO> queryReportsExport(String userId, String userAreaId, Short checkStatus, String userUnit,
			String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {
		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(userAreaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(userAreaId);
		for (Area area : list) {
			areaIds.add(area.getId());
		}
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}
		// 未同步到内网的
		filter.addRule(new FilterRule(FilterConstant.OR, "reportFlag", "0"));
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		ResultVO<ReportVO> voResultReport = toVoResultReport(reportServiceForWeb.queryReports(filter, page));
		return voResultReport;
	}

	// 自加，查询可以删除的报表

	public ResultVO<ReportVO> queryReportsDelete(String userAreaId, String userUnit, String reportSystem,
			String reportTypeId, String industryId, String reportVersion, Date startingReportDate,
			Date endingReportDate, Integer pageNum, String typeNo) {

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportServiceForWeb.queryReportsDelete(userAreaId, userUnit, reportSystem,
				reportTypeId, industryId, reportVersion, startingReportDate, endingReportDate, pageNum, page, typeNo));
	}

	// 自加， 根据操作人和单位查找报表

	public ResultVO<ReportVO> queryReportsByOperatorAndUnit(String userId, String userAreaId, Short checkStatus,
			String userUnit, String reportTypeNo, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "operator.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}
		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(userUnit)) {
			// String[] paras = new String[1];
			// String hql = "from User where userUnit.unitName = ?";
			// paras[0] = userUnit.trim();
			// cn.com.generaldata.os.paging.Result result =
			// userService.queryUsersHql(hql, null, paras);
			// if (result.getTotalCount() > 0) {
			// cn.com.generaldata.os.pojo.User user =
			// (cn.com.generaldata.os.pojo.User) result.getOperationResult()
			// .get(0);
			filter.addRule(new FilterRule(FilterConstant.LIKE, "reportUnit", "%" + userUnit.trim() + "%"));
			// }
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 自加， 根据用户地区和企位查找报表

	public ResultVO<ReportVO> queryReportsByAreaAndIndustry(String userId, String userAreaId, Short checkStatus,
			String userUnitIndustry, String reportTypeNo, Date startingReportDate, Date endingReportDate,
			Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (userUnitIndustry != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportUnitIndustry", userUnitIndustry));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		}

		filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportReferenceId", ""));

		// filter.addRule(new FilterRule(FilterConstant.NOT_NULL,
		// "reportUnitIndustry", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 自加，查询区域企业报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryEnterpriseReportsByArea(String userAreaId, Short checkStatus, String reportSystem,
			String reportTypeNo, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (checkStatus != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
		}

		if (userAreaId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}

		if (StringUtils.isNotBlank(reportTypeNo)) {
			// Get the report type by typeNo;
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeNo", reportTypeNo.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				cn.com.generaldata.os.newpojo.ReportType reportType = (cn.com.generaldata.os.newpojo.ReportType) result
						.getOperationResult().get(0);
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportType.getId()));
			}
		} else if (!StringUtils.isNotBlank(reportTypeNo) && StringUtils.isNotBlank(reportSystem)) {
			Filter typeFilter = new Filter();
			StatSystem ss = statSystemService.getStatSystemByName(reportSystem.trim());
			if (ss != null) {
				typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", ss.getId()));
			}
			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}

		// 获取最高版本的报表信息
		if (StringUtils.isBlank(reportVersion)) {
			Filter versionFilter = new Filter();
			versionFilter.setOrder(FilterConstant.DESC);
			versionFilter.setSortBy("versionNumber");
			String maxVersion = reportServiceForWeb.queryReportMaxVersion(versionFilter, null);
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", maxVersion));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 根据用户及代填用户查询报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByUserAndProxy(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (userId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", userId));
		}

		if (reportProxyId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportProxyId", reportProxyId));
		}

		if (checkStatus != null) {
			if (ReportConstant.FLAG_UNCOMMITTED == checkStatus) {
				filter.addRule(new FilterRule(FilterConstant.ORVALUE, "reportCheckStatus", checkStatus, Short
						.valueOf(ReportConstant.FLAG_PROVINCE_REJECTED)));
			} else {
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportCheckStatus", checkStatus));
			}
		}

		// 省驳回企业上报

		if (StringUtils.isNotBlank(reportTypeCode)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportTypeId", reportTypeCode));
		} else if (!StringUtils.isNotBlank(reportTypeCode) && StringUtils.isNotBlank(reportSystem)) {
			Filter typeFilter = new Filter();
			typeFilter.addRule(new FilterRule(FilterConstant.EQUAL, "typeSystem", reportSystem.trim()));

			cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReportTypes(typeFilter, null);
			if (result.getTotalCount() > 0) {
				List<cn.com.generaldata.os.newpojo.ReportType> reportTypes = (List<cn.com.generaldata.os.newpojo.ReportType>) result
						.getOperationResult();
				String[] arrIds = new String[reportTypes.size()];
				for (int i = 0; i < reportTypes.size(); i++) {
					arrIds[i] = reportTypes.get(i).getId();
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "reportTypeId", arrIds));
			}
		}

		// 获取最高版本的报表信息
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportVersion", reportVersion));

		filter.addRule(new FilterRule(FilterConstant.OR, "reportReferenceId", ""));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			filter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, page));
	}

	// 根据用户及代填用户查询报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByParent(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, String areaId, Integer pageNum, String typeNo) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportServiceForWeb.queryReportsByParent(reportProxyId, userId, checkStatus,
				reportSystem, reportTypeCode, reportVersion, startingReportDate, endingReportDate, areaId, pageNum,
				page, typeNo));
	}

	// 根据用户及代填用户查询报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByParentForWebUnit(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, String areaId, Integer pageNum, String typeNo) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportServiceForWeb.queryReportsByParentForWebUnit(reportProxyId, userId, checkStatus,
				reportSystem, reportTypeCode, reportVersion, startingReportDate, endingReportDate, areaId, pageNum,
				page, typeNo));
	}

	public List<String> queryReportTypesUnit(String unitId) {

		return reportServiceForWeb.queryReportTypesUnit(unitId);
	}

	// 取得版本类型（自己用到的）

	public List<SystemCodedic> queryTypeNew(String unitId) {
		List<SystemCodedic> list = Lists.newArrayList();
		Map<String, String> statSystems = reportServiceForWeb.queryStatSystem(unitId);
		for (Entry<String, String> entry : statSystems.entrySet()) {
			SystemCodedic sc = new SystemCodedic();
			sc.setCode(entry.getKey());
			sc.setCodeName(entry.getValue());
			list.add(sc);
		}
		return list;
	}

	// 根据用户及代填用户查询报表
	@SuppressWarnings("unchecked")
	public ResultVO<ReportVO> queryReportsByProxy(String reportProxyId, String userId, Short checkStatus,
			String reportSystem, String reportTypeCode, String reportVersion, Date startingReportDate,
			Date endingReportDate, String areaId, Integer pageNum, String flag, String createYear, String tunitName) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportServiceForWeb.queryReportsByProxy(reportProxyId, userId, checkStatus,
				reportSystem, reportTypeCode, reportVersion, startingReportDate, endingReportDate, areaId, pageNum,
				page, flag, createYear, tunitName));

	}

	// 自加,根据reportId查找该列表记录

	public List<ReportVO> queryReportsByReportId(String reportId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("reportLastEditTime");

		if (reportId != null) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "reportReferenceId", reportId));
		}

		return toVoResultReport(reportServiceForWeb.queryReports(filter, null)).getOperationResult();
	}

	@SuppressWarnings("unchecked")
	public void batchChangeStatus(Short checkStatus, List<String> ids, String operatorId, String common) {
		if (checkStatus != null && ids != null && ids.size() > 0) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", arrIds));
			List<cn.com.generaldata.os.pojo.Report> reports = (List<cn.com.generaldata.os.pojo.Report>) reportServiceForWeb
					.queryReports(filter, null).getOperationResult();

			for (cn.com.generaldata.os.pojo.Report report : reports) {
				report.setReportCheckStatus(checkStatus);
				if (common != null)
					report.setReportCheckComment(common);
				User operator = userService.queryUserById(operatorId);
				report.setOperator(operator);
				// FLAG_PASSED=6:总局审核通过
				// FLAG_PROVINCE_PASSED_UNCOMMITTED=2:省审核通过企业上报未提交总局
				if (checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PASSED).shortValue()
						|| checkStatus.shortValue() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_UNCOMMITTED)
								.shortValue()) {
					report.setReportCheckSuccessDate(new Date());
				}
				if (checkStatus.shortValue() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) {
					report.setReportCheckStatus(ReportConstant.FLAG_PROVINCE_PASSED_COMMITTED);
				}
				// 改变报表的状态
				reportServiceForWeb.modifyReport(report);
				String comment = report.getReportCheckResult();

				// 记录历史，并进行留痕操作
				// FLAG_PASSED=6:总局审核通过
				if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PASSED).shortValue()) {
					// markingService.mark4Passing(toMVCReport(report,
					// getReportDetails(report.getId())));
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					//
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_REJECTED).shortValue()) { // FLAG_REJECTED
					// = 7;
					// 总局驳回
					// markingService.mark4Rejecting(toMVCReport(report,
					// getReportDetails(report.getId())));
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PRE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_UNCOMMITTED =
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// 2; 初审通过
					comment = "初审通过";
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_REJECTED)
						.shortValue()) { // FLAG_PROVINCE_REJECTED
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// //省驳回企业上报
					comment = "驳回报表";
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_COMMITTED).shortValue()) { // FLAG_COMMITTED
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					// 企业提交省区未审核
					comment = "提交报表,待审核";
				} else if (report.getReportCheckStatus() == new Byte(ReportConstant.FLAG_PROVINCE_PASSED_COMMITTED)
						.shortValue()) { // FLAG_PROVINCE_PASSED_COMMITTED = 5;
					reportServiceForWeb.saveReportUtil(report.getId(), operator.getUserUnit().getId(),
							report.getReportCheckStatus(), report.getArea().getId());
					comment = "提交报表,待审核";
					// //省审核通过企业上报并提交总局
					if (reportServiceForWeb.checkOperatorIsBest(report.getOperator().getId()))
						comment = "审核通过";
				}

				historyService.buildHistory(new cn.com.generaldata.os.pojo.ReportHistory(null, report.getOperator(),
						report, report.getReportCheckStatus(), report.getReportCheckComment(), comment, new Date()));
			}
		}
	}

	public void removeReports(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			reportServiceForWeb.removeReports(arrIds);
		}
	}

	// 新建报表类别

	public String createReportType(String reportName) {

		// reportServiceForWeb.queryReportTypes(filter, null)
		//
		// String reportid = reportServiceForWeb.createReportType(reportType);

		return "";
	}

	public ReportTypeVO queryReportTypeById(String id) {
		cn.com.generaldata.os.newpojo.ReportType typeById = reportTypeService.getReportTypeById(id);
		List<SystemCodedic> queryType = queryType();
		return toVoReportType(typeById, queryType);
	}

	public List<ReportTypeVO> queryReportTypes() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("id");
		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "id", null));
		return toVoListReportType(reportServiceForWeb.queryReportTypes(filter, null));
	}

	@At("/company/report/queryReportTypesByParam/?/?")
	@Ok("json")
	public List<ReportTypeVO> queryReportTypesByParam(String version, String type) {
		String hql = "from ReportType as rt where rt.versionId=:version and statSystem=:statSystem order by rt.statSystem,rt.sortNo,rt.subSortNo";
		HashMap map = new HashMap();
		map.put("version", Integer.valueOf(version));
		map.put("statSystem", Integer.valueOf(type));
		cn.com.generaldata.os.paging.Result hqlParam = reportServiceForWeb.queryReportTypeByHql(hql, map, null);
		return toVoListReportType(hqlParam);
	}

	public List<ReportTypeVO> queryReportTypesByUserId(String userId) {
		if (userId != null) {
			User user = userService.queryUserById(userId);
			if (user.getUserIndustrys() != null) {
				Set<UserIndustry> industrys = user.getUserIndustrys();
				List<SystemCodedic> queryType = queryType();
				List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
				for (UserIndustry industry : industrys) {
					Set<DustryReport> dustryReports = industry.getIndustry().getDustryReports();

					for (DustryReport dustryReport : dustryReports) {
						cn.com.generaldata.os.newpojo.ReportType typeById = reportTypeService
								.getReportTypeById(dustryReport.getReportTypeId());
						ReportTypeVO voReportType = toVoReportType(typeById, queryType);
						if (voReportType != null && voReportType.getTypeCode() != null) {
							reportTypes.add(voReportType);
						}
					}
				}

				Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {

					@Override
					public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
						return rt1.getTypeCode().compareTo(rt2.getTypeCode());
					}
				});
				return reportTypes;
			}

		}
		return new ArrayList<ReportTypeVO>();
	}

	// 查询所选用户尚未提交的报表类型,自加(省区局使用)

	public ResultVO<ReportTypeVO> queryUncommittedReportTypesByUserId(String eUserLoginname, short checkStatus,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {

		Filter filter = new Filter();
		Filter reportFilter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("typeNo");

		Filter userFilter = new Filter();

		if (StringUtils.isNotBlank(eUserLoginname)) {
			userFilter.addRule(new FilterRule(FilterConstant.EQUAL, "userLoginname", eUserLoginname));
			// System.out.println(eUserLoginname);
		}

		cn.com.generaldata.os.paging.Result uResult = userService.queryUsers(userFilter, null);

		if (uResult.getOperationResult().size() > 0) {
			User eUser = (User) uResult.getOperationResult().get(0);
			reportFilter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", eUser.getId()));
			List<cn.com.generaldata.os.newpojo.ReportType> pReportTypes = new ArrayList<cn.com.generaldata.os.newpojo.ReportType>();
			if (eUser.getUserIndustrys() != null) {
				Set<UserIndustry> industrys = eUser.getUserIndustrys();
				for (UserIndustry industry : industrys) {
					pReportTypes
							.addAll(reportServiceForWeb.queryReportTypeByIndustryId(industry.getIndustry().getId()));
				}
			}
			String[] ids = new String[pReportTypes.size()];
			for (int i = 0; i < pReportTypes.size(); i++) {
				ids[i] = pReportTypes.get(i).getId();
			}
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", ids));
		}

		reportFilter.addRule(new FilterRule(FilterConstant.GT, "reportCheckStatus", checkStatus));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			reportFilter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			reportFilter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReports(reportFilter, null);

		List<cn.com.generaldata.os.pojo.Report> pReports = (List<cn.com.generaldata.os.pojo.Report>) result
				.getOperationResult();

		Set set = new HashSet();
		if (result.getOperationResult().size() > 0) {
			for (int i = 0; i < pReports.size(); i++) {
				set.add(pReports.get(i).getReportTypeId());
			}
			Object[] typeCodes = new Object[set.size()];
			set.toArray(typeCodes);
			filter.addRule(new FilterRule(FilterConstant.UNCOLLECTION, "id", typeCodes));
		}

		return toVoResultReportType(reportServiceForWeb.queryReportTypes(filter, page));
	}

	public String generalExcel(List<String> ids, String areaId) {
		String[] arrIds = new String[ids.size()];
		ids.toArray(arrIds);

		String excel = reportTemplate.generalExcel(ids, areaId);
		return excel;
	}

	public String deleteReports(List<String> ids) {
		reportEIService.deleteReports(ids);
		return null;
	}

	// 查询所选用户尚未提交的报表类型,自加(总局使用)

	public ResultVO<ReportTypeVO> queryUncommittedReportTypesByOperatorId(String eUserLoginname, short checkStatus,
			Date startingReportDate, Date endingReportDate, Integer pageNum) {
		Filter filter = new Filter();
		Filter reportFilter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("typeNo");

		Filter userFilter = new Filter();

		if (StringUtils.isNotBlank(eUserLoginname)) {
			userFilter.addRule(new FilterRule(FilterConstant.EQUAL, "userLoginname", eUserLoginname));
			// System.out.println(eUserLoginname);
		}

		cn.com.generaldata.os.paging.Result uResult = userService.queryUsers(userFilter, null);

		if (uResult.getOperationResult().size() > 0) {
			User eUser = (User) uResult.getOperationResult().get(0);
			reportFilter.addRule(new FilterRule(FilterConstant.EQUAL, "operator.id", eUser.getId()));
		}

		reportFilter.addRule(new FilterRule(FilterConstant.GT, "reportCheckStatus", checkStatus));

		if (startingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(startingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			reportFilter.addRule(new FilterRule(FilterConstant.GE, "reportDate", calendar.getTime()));
		}

		if (endingReportDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endingReportDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.add(Calendar.DATE, 1);

			reportFilter.addRule(new FilterRule(FilterConstant.LT, "reportDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}

		cn.com.generaldata.os.paging.Result result = reportServiceForWeb.queryReports(reportFilter, null);

		List<cn.com.generaldata.os.pojo.Report> pReports = (List<cn.com.generaldata.os.pojo.Report>) result
				.getOperationResult();

		Set set = new HashSet();
		if (result.getOperationResult().size() > 0) {
			for (int i = 0; i < pReports.size(); i++) {
				set.add(pReports.get(i).getReportTypeId());
			}
			Object[] typeCodes = new Object[set.size()];
			set.toArray(typeCodes);
			filter.addRule(new FilterRule(FilterConstant.UNCOLLECTION, "id", typeCodes));
		}

		return toVoResultReportType(reportServiceForWeb.queryReportTypes(filter, page));
	}

	public List<ReportTypeVO> queryReportTypesByIndustryId(String industryId) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();

		if (StringUtils.isNotBlank(industryId)) {
			List<SystemCodedic> queryType = queryType();
			for (cn.com.generaldata.os.newpojo.ReportType pReportType : reportServiceForWeb
					.queryReportTypeByIndustryId(industryId)) {
				ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
				if (voReportType != null && voReportType.getTypeCode() != null) {
					reportTypes.add(voReportType);
				}
			}
		}

		Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {

			@Override
			public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
				return rt1.getTypeCode().compareTo(rt2.getTypeCode());
			}
		});

		return reportTypes;
	}

	public List<ReportTypeVO> queryReportTypesByPara(String industryId, String code, String version) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();

		if (StringUtils.isNotBlank(industryId)) {
			List<SystemCodedic> queryType = queryType();
			List<cn.com.generaldata.os.newpojo.ReportType> queryReportTypeByIndustryId = reportServiceForWeb
					.queryReportTypeByIndustryId(industryId);
			for (cn.com.generaldata.os.newpojo.ReportType pReportType : queryReportTypeByIndustryId) {
				ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
				if (voReportType != null && voReportType.getTypeCode() != null) {
					if (code != null && !"".equals(code)) {
						if (code.equals(voReportType.getTypeCode())) {
							if (version != null && !"".equals(version)) {
								if (version.equals(voReportType.getVersionId())) {
									reportTypes.add(voReportType);
								}
							} else {
								reportTypes.add(voReportType);
							}
						}
					} else {
						if (version != null && !"".equals(version)) {
							if (version.equals(voReportType.getVersionId())) {
								reportTypes.add(voReportType);
							}
						} else {
							reportTypes.add(voReportType);
						}
					}
				}
			}
		}

		Collections.sort(reportTypes, new Comparator<ReportTypeVO>() {

			@Override
			public int compare(ReportTypeVO rt1, ReportTypeVO rt2) {
				return rt1.getTypeCode().compareTo(rt2.getTypeCode());
			}
		});
		return reportTypes;
	}

	public String exportPassedReports(String userId, String areaId) {
		try {
			String path = exporter.export(userId, areaId);
			String webRootPath = new ClassPathResource("/").getFile().getParentFile().getParentFile().getAbsolutePath();
			String pathZip = webRootPath + File.separator + "export.zip";
			// System.out.println("pathZip: " + pathZip);
			// 增加压缩工具
			ZipCompressor zip = new ZipCompressor(pathZip);
			zip.compress(path);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		url = "http://localhost:8080/jsme-das-lan/export.zip";

		// urlList.add(url);
		// return urlList;
		return url;
	}

	public boolean importReports() {
		String importRootPath = EXPORT_ROOT_DIR + File.separator + EXPORT_ROOT_DIR_1 + File.separator;
		String backupRootPath = EXPORT_ROOT_DIR + File.separator + EXPORT_FILE_BACKUP + File.separator;

		List<cn.com.generaldata.os.pojo.mvc.Report> mvcReports;
		try {
			mvcReports = Importer.importReports(importRootPath, backupRootPath);
			for (int i = 0; i < mvcReports.size(); i++) {
				reportServiceForWeb.createMVCReport((mvcReports.get(i)));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return true;
	}

	public List<ReportHistoryVO> showHistory(String reportId) {
		return toVoReportHistory(historyService.showHistory(reportId));
	}

	public List<ReportMarkingVO> showReportMarking(String reportId) {
		return toVoReportMarking(markingService.showMarking(reportId));
	}

	public void setExporter(Exporter exporter) {
		this.exporter = exporter;
	}

	private ReportVO toVoReport(cn.com.generaldata.os.pojo.Report pReport) {
		if (pReport != null) {
			String userId = pReport.getUser() == null ? null : pReport.getUser().getId();
			String operatorId = pReport.getOperator() == null ? null : pReport.getOperator().getId();
			User operator = pReport.getOperator();
			String reportProxyId = pReport.getReportProxyId();
			Unit queryUnitById = unitService.getUserUnit(reportProxyId);
			String operatorName = null;
			String areaId = pReport.getArea() == null ? null : pReport.getArea().getId();
			pReport.setReportCityName(pReport.getArea().getAreaName());
			String reportUnit = pReport.getReportUnit();
			if (queryUnitById != null)
				reportUnit = queryUnitById.getUnitName();
			//				else
			//					pReport.setReportRemark(pReport.getReportUnit());
			if (pReport.getReportTimetype() == "" || pReport.getReportTimetype() == null
					|| pReport.getReportTimetype() == "null" || pReport.getReportTimetype().equals("")
					|| pReport.getReportTimetype().equals(null) || pReport.getReportTimetype().equals("null")) {
				pReport.setReportTimetype("");
			}
			if (pReport.getReportUnitIndustry() == "" || pReport.getReportUnitIndustry() == null
					|| pReport.getReportUnitIndustry() == "null" || pReport.getReportUnitIndustry().equals("")
					|| pReport.getReportUnitIndustry().equals(null) || pReport.getReportUnitIndustry().equals("null")) {
				pReport.setReportUnitIndustry("");
			}
			if (pReport.getReportReferenceId() == "" || pReport.getReportReferenceId() == null
					|| pReport.getReportReferenceId() == "null" || pReport.getReportReferenceId().equals("")
					|| pReport.getReportReferenceId().equals(null) || pReport.getReportReferenceId().equals("null")) {
				pReport.setReportReferenceId("");
			}

			return new ReportVO(pReport.getId(), pReport.getReportReferenceId(), userId, operatorId, operatorName,
					areaId, pReport.getReportType(), pReport.getReportTypeCode(), pReport.getReportName(),
					pReport.getReportRegionName(), pReport.getReportRegionOcean(), pReport.getReportCityName(),
					pReport.getReportDepartmentName(), pReport.getReportRegionCode(), pReport.getReportUnit(),
					pReport.getReportUnitIndustry(), pReport.getReportInstitutionName(),
					pReport.getReportInstitutionCode(), pReport.getReportDomainName(), pReport.getReportDomainCode(),
					pReport.getReportYear(), pReport.getReportQuarter(), pReport.getReportNo(),
					pReport.getReportAdmin(), pReport.getReportApproveAdmin(), pReport.getReportApproveNo(),
					pReport.getReportExpireDate(), pReport.getReportMeasureUnit(), pReport.getReportUnitAdmin(),
					pReport.getReportStatAdmin(), pReport.getReportFillAdmin(), pReport.getReportDate(),
					pReport.getReportCreateTime(), pReport.getReportLastEditTime(), pReport.getReportCheckStatus(),
					pReport.getReportCheckComment(), pReport.getReportCheckSuccessDate(), pReport.getReportOrigin(),
					pReport.getReportSupplyOrigin(), pReport.getReportDesc(), pReport.getReportCheckResult(),
					pReport.getReportRemark(), pReport.getReportFlag(), pReport.getReportProxyId(),
					pReport.getReportTimetype(), pReport.getReportMonth(), pReport.getReportYearTime(),
					pReport.getReportTypeId(), pReport.getReportEdition(), pReport.getReportVersion(),
					pReport.getUnitId(), pReport.getMonth(), pReport.getQuarter(), pReport.getUpdateTime());

		}
		return null;
	}

	private VersionVO toVoVersion(ReportVersion pVersion) {
		if (pVersion != null) {
			return new VersionVO(pVersion.getId().toString(), pVersion.getVersionNumber(), pVersion.getVersionName(),
					pVersion.getCreateTime(), pVersion.getStatSystem());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportVO> toVoResultReport(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportVO> result = new ResultVO<ReportVO>();

		List<ReportVO> reports = new ArrayList<ReportVO>();
		for (cn.com.generaldata.os.pojo.Report pReport : (List<cn.com.generaldata.os.pojo.Report>) pResult
				.getOperationResult()) {
			ReportVO voReport = toVoReport(pReport);
			if (voReport != null) {
				reports.add(voReport);
			}
		}
		result.setOperationResult(reports);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<VersionVO> toVoResultVersion(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<VersionVO> result = new ResultVO<VersionVO>();

		List<VersionVO> versions = new ArrayList<VersionVO>();
		for (ReportVersion pVersion : (List<ReportVersion>) pResult.getOperationResult()) {
			VersionVO voVersion = toVoVersion(pVersion);
			if (voVersion != null) {
				versions.add(voVersion);
			}
		}
		result.setOperationResult(versions);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<ReportTypeVO> toVoResultReportType(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<ReportTypeVO> result = new ResultVO<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		for (cn.com.generaldata.os.newpojo.ReportType pReportType : (List<cn.com.generaldata.os.newpojo.ReportType>) pResult
				.getOperationResult()) {
			ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		result.setOperationResult(reportTypes);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	private ReportTypeVO toVoReportType(cn.com.generaldata.os.newpojo.ReportType pReportType,
			List<SystemCodedic> queryType) {
		if (pReportType != null) {
			String type = "";
			for (SystemCodedic sc : queryType) {
				if (sc.getCode().equals(pReportType.getStatSystem().toString())) {
					type = sc.getCodeName();
					break;
				}
			}
			String name = pReportType.getTypeName();
			if (pReportType.getTypeNo() != null)
				name = pReportType.getTypeNo() + "-" + pReportType.getTypeName();
			return new ReportTypeVO(pReportType.getId(), name, pReportType.getTypeNo(), pReportType.getStatSystem()
					.toString(), pReportType.getTypeReportAdmin().toString(), pReportType.getTypeApproveAdmin()
					.toString(), pReportType.getTypeApproveNo(), pReportType.getTypeExpireDate(),
					pReportType.getTypeMeasureUnit(), pReportType.getTypeLastTime() == null ? 0 : pReportType
							.getTypeLastTime().shortValue(), pReportType.getTypeYearTime(), pReportType.getTypeTime(),
					type, pReportType.getVersionId().toString(), pReportType.getId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private List<ReportTypeVO> toVoListReportType(cn.com.generaldata.os.paging.Result pResult) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		for (cn.com.generaldata.os.newpojo.ReportType pReportType : (List<cn.com.generaldata.os.newpojo.ReportType>) pResult
				.getOperationResult()) {
			ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		return reportTypes;
	}

	public boolean checkReportViewStatus(String userId, String reportId) {
		if (null == userId || userId.trim().length() == 0) {
			return false;
		}

		if (null == reportId || reportId.trim().length() == 0) {
			return false;
		}

		User user = userService.queryUserById(userId);
		if (null == user) {
			return false;
		}

		cn.com.generaldata.os.pojo.Report dReport = reportServiceForWeb.queryReportById(reportId);
		if (null == dReport) {
			return false;
		}
		ReportVO report = toVoReport(dReport);

		boolean result = true;
		if ("Enterprise".equals(user.getRole().getRoleDesc())) {
			if (ReportConstant.FLAG_COMMITTED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_PASSED == report.getReportCheckStatus()) {
				result = false;
			}
		} else if ("Ocean".equals(user.getRole().getRoleDesc())) {
			if (ReportConstant.FLAG_UNCOMMITTED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_PASSED == report.getReportCheckStatus()
					|| ReportConstant.FLAG_REJECTED == report.getReportCheckStatus()) {
				result = false;
			}
		} else {
			result = false;
		}
		return result;
	}

	private List<ReportHistoryVO> toVoReportHistory(List<cn.com.generaldata.os.pojo.ReportHistory> pHistories) {
		List<ReportHistoryVO> result = new ArrayList<ReportHistoryVO>();
		for (cn.com.generaldata.os.pojo.ReportHistory pHistory : pHistories) {
			ReportHistoryVO reportHistory = new ReportHistoryVO(pHistory.getId(), pHistory.getOperator().getId(),
					pHistory.getOperator().getUserLoginname(), pHistory.getOperator().getUserUnit().getUnitName(),
					pHistory.getReport().getId(), pHistory.getReportStatus(), pHistory.getReportCheckComment(),
					pHistory.getReportCheckResult(), pHistory.getHistoryDate());
			reportHistory.setReportCheckResult(pHistory.getOperator().getUserUnit().getUnitName()
					+ pHistory.getReportCheckResult());
			result.add(reportHistory);
		}
		return result;
	}

	// 自加
	private List<ReportMarkingVO> toVoReportMarking(List<cn.com.generaldata.os.pojo.ReportMarking> pReportMarkings) {
		List<ReportMarkingVO> result = new ArrayList<ReportMarkingVO>();
		for (cn.com.generaldata.os.pojo.ReportMarking pReportMarking : pReportMarkings) {
			result.add(new ReportMarkingVO(pReportMarking.getId(), pReportMarking.getReport().getId(), pReportMarking
					.getOperator().getId(), pReportMarking.getOperator().getUserLoginname(), pReportMarking
					.getReportStatus(), pReportMarking.getMarkingDate(), pReportMarking.getMarkingContent()));
		}
		return result;
	}

	private cn.com.generaldata.os.pojo.mvc.Report toMVCReport(cn.com.generaldata.os.pojo.Report report,
			List<ReportDetail> reportDetails) {
		List<Row> rows = new ArrayList<Row>();
		for (ReportDetail reportDetail : reportDetails) {
			Row row = BeanMapper.map(reportDetail, Row.class);
			row.setRowId(reportDetail.getId());
			rows.add(row);
		}

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		return new cn.com.generaldata.os.pojo.mvc.Report(String.valueOf(report.getId()), String.valueOf(report
				.getReportReferenceId()), report.getReportType(), report.getReportTypeCode(), String.valueOf(report
				.getUser().getId()), report.getReportRegionName(), report.getReportRegionOcean(),
				report.getReportCityName(), report.getReportDepartmentName(), report.getReportRegionCode(),
				report.getReportUnit(), report.getReportUnitIndustry(), report.getReportUnitIndustryId(),
				report.getReportInstitutionName(), report.getReportInstitutionCode(), report.getReportDomainName(),
				report.getReportDomainCode(), report.getReportYear(), report.getReportQuarter(), report.getReportNo(),
				report.getReportAdmin(), report.getReportApproveAdmin(), report.getReportApproveNo(),
				report.getReportExpireDate(), report.getReportMeasureUnit(), report.getReportUnitAdmin(),
				report.getReportStatAdmin(), report.getReportFillAdmin(), formatter.format(report.getReportDate()),
				report.getReportOrigin(), report.getReportSupplyOrigin(), report.getReportDesc(),
				report.getReportCreateTime(), report.getReportLastEditTime(), String.valueOf(report.getOperator()
						.getId()), String.valueOf(report.getArea().getId()), Byte.valueOf(String.valueOf(report
						.getReportCheckStatus())), report.getReportCheckComment(), report.getReportCheckResult(),
				report.getReportCheckSuccessDate(), report.getReportRemark(), report.getReportFlag(),
				report.getReportProxyId(), rows, report.getReportTimetype(), report.getReportMonth(),
				report.getReportYearTime(), report.getReportVersion(), report.getReportTypeId(),
				report.getReportEdition(), report.getSelfSet1(), report.getSelfSet2(), report.getSelfSet3(),
				report.getSelfSet4(), report.getSelfSet5(), report.getQuarter(), report.getMonth(), report.getUnitId(),
				report.getUpdateTime());
	}

	@SuppressWarnings("unchecked")
	private List<ReportDetail> getReportDetails(String reportId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("rowIndex");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "report.id", reportId));
		return (List<ReportDetail>) reportServiceForWeb.queryReportDetails(filter, null).getOperationResult();
	}

	// 导出所有报表模板

	public Boolean exportReportType() {
		return reportEIService.exportReportType();
	}

	// 将业务库的终审通过或驳回报表导到导出库

	public Boolean exportEIReport(List<String> ids) {
		//		String[] arrIds = new String[ids.size()];
		//		ids.toArray(arrIds);
		//
		//		Filter filter = new Filter();
		//		filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", arrIds));
		//		cn.com.generaldata.os.paging.Result export = reportServiceForWeb.queryReports(filter, null);
		//		if (export != null) {
		//			List<Report> result = export.getOperationResult();
		Set<String> ridSet = new HashSet<String>();
		//			String[] rids = new String[result.size()];
		for (int i = 0; i < ids.size(); i++) {
			ridSet.add(ids.get(i));
			//				rids[i] = ;parReport.toArray(new String[] {})
		}
		if (!ridSet.isEmpty()) {
			reportEIService.exportEIReport(ridSet);

		}

		return true;
	}

	// 将业务库的已更新用户导入到导出库

	public boolean importUser() {

		return reportEIService.importUser();

	}

	// 更改用户导出完成状态

	public boolean exportOverUser(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			return reportEIService.exportOverUser(arrIds);
		}
		return false;
	}

	// 将导出入库导入到业务库的已上报报表

	public ResultVO<ReportVO> importEIReport(int pageNumber, int PageSize) {
		ResultVO<ReportVO> result = new ResultVO<ReportVO>();
		List<ReportVO> reports = new ArrayList<ReportVO>();

		reportEIService.importEIReport();
		return null;
	}

	// 自动清除导入库的数据

	public Boolean cleanEIReport() {
		return reportEIService.cleanEIReport();
	}

	public ResultVO<ReportVO> queryAllReport(String areaId, String unitName, String reportSystem, String reportTypeId,
			String industryId, String reportVersion, Date startingReportDate, Date endingReportDate, Integer pageNum,
			String status, String typeNo) {
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, 20);
		}
		return toVoResultReport(reportServiceForWeb.queryAllReport(areaId, unitName, reportSystem, reportTypeId,
				industryId, reportVersion, startingReportDate, endingReportDate, pageNum, page, status, typeNo));

	}

	// 获取已经激活的所有的版本信息
	@At("/company/report/queryReportVersion/?")
	@Ok("json")
	public ResultVO<VersionVO> queryReportVersion(String code) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("endDate");
		if (code == null) {
			code = "1";
		}
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", Integer.valueOf(code)));
		return toVoResultVersion(reportServiceForWeb.queryReportVersion(filter, null));
	}

	// 按年份查询版本

	public VersionVO queryVersionByYear(Date date, String type) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		filter.addRule(new FilterRule(FilterConstant.LE, "startDate", date));
		filter.addRule(new FilterRule(FilterConstant.GE, "endDate", date));
		if (type == null) {
			type = "1";
		}
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", Integer.valueOf(type)));
		cn.com.generaldata.os.paging.Result reportVersion = reportServiceForWeb.queryReportVersion(filter, null);
		if (reportVersion != null && reportVersion.getTotalCount() > 0) {
			List<ReportVersion> operationResult = (List<ReportVersion>) reportVersion.getOperationResult();
			ReportVersion version = operationResult.get(0);
			return toVoVersion(version);
		}
		return null;
	}

	// 查看当前报表制度是否存在

	public VersionVO isVersionSystem(String vSystem) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		if (StringUtils.isNotBlank(vSystem)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "versionName", vSystem));
		}

		return this.toVoVersion(reportServiceForWeb.getVersion(filter, null));
	}

	// 获取最高版本的报表信息

	public String queryReportMaxVersion() {
		Filter versionFilter = new Filter();
		versionFilter.setOrder(FilterConstant.DESC);
		versionFilter.setSortBy("versionNumber");
		String maxVersion = reportServiceForWeb.queryReportMaxVersion(versionFilter, null);
		return String.valueOf(maxVersion);
	}

	public cn.com.generaldata.os.vo.ReportPerformVO reportAccount(String areaId, String timeType, String type) {
		return reportServiceForWeb.reportAccount(areaId, timeType, type);
	}

	public ReportVersionYearRangeResult getReportVersionYearRange() {
		ReportVersionYearRangeResult result = new ReportVersionYearRangeResult();

		Date startYear = indicatorSystemSqlTemplate.queryForObject("SELECT MIN(start_date) FROM tbl_report_version ",
				null, Date.class);
		Date endYear = indicatorSystemSqlTemplate.queryForObject("SELECT MAX(end_date) FROM tbl_report_version ", null,
				Date.class);
		Calendar cal = Calendar.getInstance();
		cal.setTime(startYear);
		result.setStartYear(cal.get(Calendar.YEAR));
		cal.setTime(endYear);
		result.setEndYear(cal.get(Calendar.YEAR));
		return result;
	}

	/**
	 * 绩效评估.
	 * @param year
	 * @param month
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/company/performance/evaluation")
	@Ok("jsp:/static/company/performance/list")
	public ResultVO<ReportPerformVO> performanceEvaluation(@Param("year") String year, @Param("month") String month,
			HttpServletRequest request, HttpSession session) {

		//年份范围
		ReportVersionYearRangeResult yearRange = getReportVersionYearRange();
		int startYear = yearRange.getStartYear();
		int endYear = yearRange.getEndYear();

		//年份列表
		List<Integer> years = new ArrayList<Integer>();
		for (int i = endYear; i >= startYear; i--) {
			years.add(i);
		}
		request.setAttribute("years", years);

		//月份列表
		List<Integer> months = new ArrayList<Integer>();
		for (int i = 1; i <= 12; i++) {
			months.add(i);
		}
		request.setAttribute("months", months);

		//当前用户的企业ID
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String areaId = voUser.getUserUnitId();

		//年月
		Calendar cal = Calendar.getInstance();
		if (year == null) {
			year = String.valueOf(cal.get(Calendar.YEAR));
		}
		if (month == null) {
			month = String.valueOf(cal.get(Calendar.MONTH) + 1);
		}
		request.setAttribute("selectYear", year);
		request.setAttribute("selectMonth", month);
		if (!"".equals(month)) {
			month = "/" + month;
		}

		ResultVO<ReportPerformVO> result = new ResultVO<ReportPerformVO>();

		List<ReportPerformVO> list = new ArrayList<ReportPerformVO>();
		list.add(reportServiceForWeb.reportAccount(areaId, year + month, null));

		result.setOperationResult(list);

		//查询
		return result;
	}

	@At("/company/report/fillAlert")
	@Ok("jsp:/static/company/report/fillAlert")
	public List<ReportVO> reportAlert(HttpServletRequest request, HttpSession session) {
		//当前用户ID
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		return reportServiceForWeb.reportAlert(voUser.getId());
	}

	@At("/company/report/myFillList")
	@Ok("jsp:/static/company/report/myFillList")
	public ResultVO<ReportVO> myFillList(@Param("p") int pageNum, @Param("chooseUser") String chooseUser,
			@Param("reportSystem") String reportSystem, @Param("reportDate") String reportDate,
			HttpServletRequest request, HttpSession session) {

		// 准备查询参数
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		// 报表制度列表，code是t_stat_system表的id，codename是name。
		List<SystemCodedic> systemList = this.queryType(voUser.getId(), voUser.getRoleId());
		request.setAttribute("systemList", systemList);
		//初始进来的时候没有选择项，默认一个
		if (StringUtils.isBlank(reportSystem) && systemList.size() > 0) {
			reportSystem = systemList.get(0).getCode();
		}

		String userId = voUser.getId(); // 当前用户ID
		String unitName = voUser.getUserUnit();//用户所在单位名称
		String unitId = voUser.getUserUnitId();//用户所在单位名称
		String proxyId = voUser.getId(); // 代填人ID
		//所选填报用户
		if (chooseUser != null) {
			userId = chooseUser;
			User userById = userService.queryUserById(chooseUser);
			unitName = userById.getUserUnit().getUnitName();
			unitId = userById.getUserUnit().getId();
		}
		request.setAttribute("unitName", unitName);
		request.setAttribute("chooseUser", userId);
		request.setAttribute("unitId", unitId);
		// 页数
		if (pageNum == 0) {
			pageNum = 1;
		}
		Date reportTime = new Date();
		//报表时间
		if (StringUtils.isNotBlank(reportDate))
			try {
				reportTime = sfd.parse(reportDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		request.setAttribute("reportDate", sfd.format(reportTime));
		List<ReportVO> reportAllQuery = reportAllQuery(userId, reportSystem, reportTime, proxyId);
		ResultVO<ReportVO> result = new ResultVO<ReportVO>();

		result.setOperationResult(reportAllQuery);
		result.setPageNumber(1);
		result.setPageSize(1);
		result.setTotalCount(reportAllQuery.size());
		//		Result<Report> xx = this.queryReportsByProxy(reportProxyId, userId, (short) checkStatus, reportSystem,
		//				reportTypeCode, reportVersion, startReportDate, endReportDate, areaId, pageNum, flag, year, unitName);

		return result;
	}

	public List<ReportVO> reportAllQuery(String userId, String systemType, Date reportTime, String proxyId) {
		Calendar dateStart = Calendar.getInstance();
		Calendar dateEnd = Calendar.getInstance();
		Calendar dateNow = Calendar.getInstance();
		dateEnd.setTime(reportTime);
		dateStart.setTime(reportTime);
		dateStart.set(Calendar.DATE, 1);
		// 如果是当月
		if (dateNow.get(Calendar.YEAR) == dateStart.get(Calendar.YEAR)
				&& dateNow.get(Calendar.MONTH) == dateStart.get(Calendar.MONTH))
			dateEnd = Calendar.getInstance();
		else {
			int day = dateStart.getActualMaximum(Calendar.DAY_OF_MONTH);
			dateEnd.set(Calendar.DATE, day);
		}
		List<ReportVO> reportAllQuery = reportServiceForWeb.reportAllQuery(userId, systemType, dateStart.getTime(),
				dateEnd.getTime(), proxyId);

		return reportAllQuery;
	}

	// 查询当前企业所有的上传附件
	@At("/company/data/transferReportList")
	@Ok("jsp:/static/company/data/transferReportList")
	public ResultVO<ReportAttachVO> queryReportAttach(@Param("searchDate") Date searchDate,
			@Param("endDate") Date endDate, Integer pageNum, HttpSession session) {
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");

		String loginName = voUser.getId();

		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sysCreateDate");
		// 如果查询用户ID不为空，就是企业查询，管理部门传null查询全部
		if (StringUtils.isNotBlank(loginName)) {
			User userById = userService.queryUserById(loginName);
			Filter filter2 = new Filter();
			filter2.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", userById.getUserUnit().getId()));
			cn.com.generaldata.os.paging.Result result = userService.queryUsers(filter2, null);
			if (result != null) {
				List<User> operationResult = (List<User>) result.getOperationResult();
				String[] uids = new String[operationResult.size()];
				for (int i = 0; i < operationResult.size(); i++) {
					uids[i] = operationResult.get(i).getId();
				}
				if (!(operationResult.size() > 0)) {
					uids = new String[] { "" };
				}
				filter.addRule(new FilterRule(FilterConstant.COLLECTION, "userId", uids));
			} else {
				filter.addRule(new FilterRule(FilterConstant.EQUAL, "userId", loginName));
			}
		}
		// 状态为3的是管理部门发送通知的附件
		filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "isDisposal", 3));
		if (searchDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(searchDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.GE, "sysCreateDate", calendar.getTime()));
		}

		if (endDate != null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endDate);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			filter.addRule(new FilterRule(FilterConstant.LT, "sysCreateDate", calendar.getTime()));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(new Integer(1), ResultVO.DEFAULT_PAGE_SIZE);
		}

		return toVoResultReportAttach(reportServiceForWeb.queryReportAttach(filter, page));
	}
}
